package com.mayuhao.time.service;

import com.eltima.components.ui.DatePicker;
import com.mayuhao.time.dao.User;
import com.mayuhao.time.daoImpl.UserDaoImpl;
import com.mayuhao.time.date.MyDate;
import com.mayuhao.time.date.MyDateImpl;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author YHwinner
 */

public class Client extends JFrame {

    public static void main(String[] args) {
        new Client();
    }

    private JLabel date;
    private JLabel time;
    private JPanel panel;
    private JTextField textField;
    private JLabel label_time;
    private JButton button_timer;
    private JButton button_set_time;
    //同步时间按钮
    private JButton synchronised_time;
    private MyDate myDate = new MyDate();
    private MyDateImpl myDateDo = new MyDateImpl();
    private Socket socket;
    private String alter_date;

    private String user_ip;

    public Client() {

        //初始化设置时间为本地时间
//        myDateDo.setNowDateST(0);

        //初始化图形界面
        this.setTitle("宇豪的私人手表");
        this.setSize(600, 380);
        this.setLocation(600, 200);
        this.setResizable(false);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //弹窗获取ip
        user_ip = JOptionPane.showInputDialog(null, "请输入您的IP地址：");
        if (user_ip.equals("")) System.exit(0);
        this.setVisible(true);

        panel = new JPanel();
        panel.setBackground(new Color(116, 226, 234, 255));
        getContentPane().add(panel, BorderLayout.CENTER);
        panel.setLayout(null);

        //时间
        time = new JLabel();
        time.setBounds(31, 90, 800, 59);
        time.setFont(new Font("Arial", Font.PLAIN, 60));
        time.setForeground(new Color(159, 42, 236));
        panel.add(time);
        //日期
        date = new JLabel();
        date.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        date.setBounds(47, 60, 300, 22);
        date.setForeground(new Color(241, 109, 3));
        panel.add(date);

        //显示修改时间组件及监听
        showButton();

        //显示同步时间按钮
        synchronisedTime();

        //显示闹钟组件及监听
        showClock();

        //下拉框
        comBoBox();

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(new MyThread());
        executorService.shutdown();
    }

    //设置时区的下拉框
    public void comBoBox() {

        JLabel jLabel = new JLabel("下拉设置时区！");
        jLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        jLabel.setBounds(440, 218, 300, 22);
        jLabel.setForeground(new Color(243, 71, 150));
        panel.add(jLabel);

        JComboBox select = new JComboBox();
        select.setBounds(380, 220, 200, 20);
        select.addItem("选择时区（默认北京时间）");

        select.addItem("中央时区，英国伦敦");
        select.addItem("东一区，法国巴黎");
        select.addItem("东二区，埃及开罗");
        select.addItem("东三区，俄罗斯莫斯科");
        select.addItem("东四区，阿联酋阿布扎比");
        select.addItem("东五区，巴基斯坦伊斯兰堡");
        select.addItem("东六区，中国新疆自治区");
        select.addItem("东七区，泰国曼谷");
        select.addItem("东八区，天朝北京");
        select.addItem("东九区，小日本东京");
        select.addItem("东十区，澳大利亚墨尔本");
        select.addItem("东十一区，所罗门群岛");
        select.addItem("东十二区，新西兰惠灵顿");
        select.addItem("西一区，非洲大陆最西边不知名的地方");
        select.addItem("西二区，大西洋中部");
        select.addItem("西三区，巴西巴西利亚");
        select.addItem("西四区，智力圣地亚哥");
        select.addItem("西五区，美国纽约");
        select.addItem("西六区，美国芝加哥");
        select.addItem("西七区，美国亚利桑那州菲尼克斯");
        select.addItem("西八区，美国加里福利亚州");
        select.addItem("西九区，美国阿拉斯加州安克雷奇");
        select.addItem("西十区，美国檀香山");
        select.addItem("西十一区，太平洋中部");
        select.addItem("西十二区，太平洋中部");

        panel.add(select);

        select.addActionListener(e -> {
            myDateDo.clearSTAdd();
            myDate.setFlag(2);
            int hour = 3600000;
//                System.out.println(select.getSelectedItem());
            if ("选择时区（默认北京时间）".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(0);
            } else if ("中央时区，英国伦敦".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * -8);
            } else if ("东一区，法国巴黎".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * -7);
            } else if ("东二区，埃及开罗".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * -6);
            } else if ("东三区，俄罗斯莫斯科".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * -5);
            } else if ("东四区，阿联酋阿布扎比".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * -4);
            } else if ("东五区，巴基斯坦伊斯兰堡".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * -3);
            } else if ("东六区，中国新疆自治区".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * -2);
            } else if ("东七区，泰国曼谷".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * -1);
            } else if ("东八区，天朝北京".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(0);
            } else if ("东九区，小日本东京".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour);
            } else if ("东十区，澳大利亚墨尔本".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 2);
            } else if ("东十一区，所罗门群岛".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 3);
            } else if ("东十二区，新西兰惠灵顿".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 4);
            } else if ("西一区，非洲大陆最西边不知名的地方".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 5);
            } else if ("西二区，大西洋中部".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 6);
            } else if ("西三区，巴西巴西利亚".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 7);
            } else if ("西四区，智力圣地亚哥".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 8);
            } else if ("西五区，美国纽约".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 9);
            } else if ("西六区，美国芝加哥".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 10);
            } else if ("西七区，美国亚利桑那州菲尼克斯".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 11);
            } else if ("西八区，美国加里福利亚州".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 12);
            } else if ("西九区，美国阿拉斯加州安克雷奇".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 13);
            } else if ("西十区，美国檀香山".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 14);
            } else if ("西十一区，太平洋中部".equals(select.getSelectedItem())) {
                myDateDo.setNowDateST(hour * 15);
            } else {
                myDateDo.setNowDateST(hour * 16);
            }
        });

    }

    //启动设置时间
    public void showButton() {
        //设置时间按钮
        button_set_time = new JButton("点击设置时间");
        button_set_time.setFont(new Font("微软雅黑", Font.PLAIN, 30));
        button_set_time.setForeground(new Color(68, 122, 222));
        button_set_time.setBounds(300, 0, 295, 100);
        //去掉按钮文字周围的焦点框
        button_set_time.setFocusPainted(false);
        panel.add(button_set_time);

        button_set_time.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                new alterGUI();
            }
        });
    }

    //时间同步按钮  触发同步服务器端的时间
    public void synchronisedTime() {
        synchronised_time = new JButton("同步时间(北京)");
        synchronised_time.setFont(new Font("微软雅黑", Font.PLAIN, 30));
        synchronised_time.setForeground(new Color(68, 122, 222));
        synchronised_time.setBounds(300, 100, 295, 100);
        //去掉按钮文字周围的焦点框
        synchronised_time.setFocusPainted(false);
        panel.add(synchronised_time);
        synchronised_time.addActionListener(e -> {
            myDateDo.clearAdd();
            try {

                socket = new Socket("127.0.0.1", 6666);
                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                dos.writeUTF("GO");
                dos.flush();

                new Thread(new SynchronisedTime()).start();

            } catch (IOException ioException) {
                ioException.printStackTrace();
                JOptionPane.showMessageDialog(null, "服务器崩啦！赶快联系马宇豪￥", "驾崩over!", JOptionPane.ERROR_MESSAGE);
            }
        });
    }

    class SynchronisedTime implements Runnable {

        @Override
        public void run() {
            try {

                DataInputStream dis = new DataInputStream(socket.getInputStream());
                String s = dis.readUTF();
                System.out.println(s);

                myDate.setYear(s.substring(0, 4));
                myDate.setMonth(s.substring(7, 9));
                myDate.setDay(s.substring(12, 14));
                myDate.setHour(s.substring(22, 24));
                myDate.setMinute(s.substring(25, 27));
                myDate.setSs(s.substring(28, 30));

                myDateDo.setMyDate(myDate.getYear(),
                        myDate.getMonth(),
                        myDate.getDay(),
                        myDate.getHour(),
                        myDate.getMinute(),
                        myDate.getSs()
                );

                myDate.setFlag(1);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    //启动闹钟
    public void showClock() {
        //文本域
        textField = new JTextField();
        textField.setBounds(20, 240, 50, 20);
        textField.setToolTipText("多久后提示您呢？");
        textField.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        panel.add(textField);

        //文字
        label_time = new JLabel("秒后提醒我！");
        label_time.setFont(new Font("微软雅黑", Font.PLAIN, 18));
        label_time.setBounds(80, 240, 200, 20);
        panel.add(label_time);

        //提交按钮
        button_timer = new JButton("提交");
        button_timer.setBounds(220, 240, 80, 26);
        button_timer.setFont(new Font("宋体", Font.BOLD, 18));
        panel.add(button_timer);

        //提交按钮事件
        button_timer.addActionListener(e -> {

            System.out.println(textField.getText());
            //避免用户随意输入定时时间 if-else
            if (!textField.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "确认设置此闹钟吗？", "闹钟提示", JOptionPane.QUESTION_MESSAGE);
                System.out.println(textField.getText());

                //将用户设置的时间发送  定时器开启
                //传入一个当前时间，给定时器做比较
                String clock_current_time = String.valueOf(System.currentTimeMillis() / 1000);
                timeClock(textField.getText(), clock_current_time);
            } else {
                JOptionPane.showMessageDialog(null, "时间不可以为空！", "输入错误", JOptionPane.ERROR_MESSAGE);

            }
        });
    }

    //用线程来更新时间
    class MyThread implements Runnable {
        @Override
        public void run() {
            try {

                while (true) {
                    System.out.println("当前标志位状态------>" + myDate.getFlag());

                    if (myDate.getFlag() == 1) {
                        date.setText(new SimpleDateFormat("yyyy 年 MM 月 dd 日   EEEE").format(myDateDo.getMyDateYmd()));
                        time.setText(new SimpleDateFormat("HH:mm:ss").format(myDateDo.getMyDateHms()));
//                        System.out.println("在mydate里面的时间" + myDateDo.getMyDateYmd());
                    } else if (myDate.getFlag() == 2) {
                        date.setText(new SimpleDateFormat("yyyy 年 MM 月 dd 日   EEEE").format(myDateDo.getNowDateYmd()));
                        time.setText(new SimpleDateFormat("HH:mm:ss").format(myDateDo.getNowDateHms()));
                    } else {
                        date.setText(new SimpleDateFormat("yyyy 年 MM 月 dd 日   EEEE").format(new Date()));
                        time.setText(new SimpleDateFormat("HH:mm:ss").format(new Date()));
                    }
                    Thread.sleep(1000);
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }

        }

    }

    //定时器
    public void timeClock(String clock_set_time, String clock_current_time) {

        //将时间转化
        int clock_int_current = Integer.parseInt(clock_current_time);
        int clock__int_set = Integer.parseInt(clock_set_time);
        //流动时间戳（作倒计时）
        int primary_time;
        //提示时间戳
        int reminder_time = clock_int_current + clock__int_set;

        while (true) {
            primary_time = Math.toIntExact((System.currentTimeMillis() / 1000));
            if (reminder_time == primary_time) {
                JOptionPane.showMessageDialog(null, "起来，不愿做奴隶的人们！", "已到时", JOptionPane.WARNING_MESSAGE);
                return;
            }
        }
    }

    //日历面板
    class alterGUI extends JPanel {
        private User user;
        private UserDaoImpl userDao;

        public alterGUI() {

            JFrame f = new JFrame("时间设置");
            f.setSize(600, 400);
            f.setLocation(200, 200);
            f.setLayout(null);

            final DatePicker datepick;
            datepick = getDatePicker();

            f.add(datepick);

            JButton b = new JButton("确认修改");
            b.setBounds(137, 183, 300, 60);
            f.add(b);
            f.setVisible(true);
            //对单击确定按钮，设置时间中数据库的封装操作
            b.addActionListener(e -> {
                //修改后清除时间差记忆
                myDateDo.clearAdd();

                //封装数据库
                user = new User();
                userDao = new UserDaoImpl();

                //日期转化
                alter_date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEEE").format(datepick.getValue());
                System.out.println(alter_date + "当前修改的");
                String user_alter_time = alter_date;
                String user_current_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEEE").format(new Date());
                user.setUser_alter_time(user_alter_time);
                user.setUser_current_time(user_current_time);
                user.setUser_ip(user_ip);

                myDate.setYear(alter_date.substring(0, 4));
                myDate.setMonth(alter_date.substring(5, 7));
                myDate.setDay(alter_date.substring(8, 10));
                myDate.setHour(alter_date.substring(11, 13));
                myDate.setMinute(alter_date.substring(14, 16));
                myDate.setSs(alter_date.substring(17, 19));

                myDateDo.setMyDate(myDate.getYear(),
                        myDate.getMonth(),
                        myDate.getDay(),
                        myDate.getHour(),
                        myDate.getMinute(),
                        myDate.getSs()
                );

                //点击修改后，flag为false，date使用修改后的时间
//                myDateDo.setFlag(1);
                //设置自定义修改时间（GUI）

                myDate.setFlag(1);

                JOptionPane.showMessageDialog(f, "修改成功！当前时间为：" + '\n' + alter_date);
                //数据库判断用户是否为新用户（存储）
                userDao.updateUserCount(user_ip);
                System.out.println(userDao.selectIp() + "还没有存储");
                //存储数据库
                userDao.insUserInfo(user.getUser_ip(),
                        user.getUser_alter_time(),
                        user.getUser_current_time()
                );
                System.out.println(userDao.selectIp() + "存储后");

            });

        }

        //日历的设置
        private DatePicker getDatePicker() {
            final DatePicker datepick;
            // 格式
            String DefaultFormat = "yyyy-MM-dd HH:mm:ss";
            // 当前时间
            Date date = new Date();
            // 字体
            Font font = new Font("Times New Roman", Font.BOLD, 25);

            Dimension dimension = new Dimension(300, 50);

            int[] hilightDays = {1, 3, 5, 7};

            int[] disabledDays = {4, 6, 5, 9};

            datepick = new DatePicker(date, DefaultFormat, font, dimension);

            datepick.setLocation(200, 83);
            datepick.setBounds(137, 83, 300, 50);
            // 设置一个月份中需要高亮显示的日子
            datepick.setHightlightdays(hilightDays, Color.red);
            // 设置一个月份中不需要的日子，呈灰色显示
            datepick.setDisableddays(disabledDays);
            // 设置国家
            datepick.setLocale(Locale.CHINA);
            // 设置时钟面板可见
            datepick.setTimePanleVisible(true);
            return datepick;
        }
    }
}